<!DOCTYPE html PUBLIC>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>后台管理中心</title>
    <link rel="stylesheet" href="/admin/css/pintuer.css"/>
    <link rel="stylesheet" href="/admin/css/admin.css"/>
    <link href="/admin/css/bootstrap.min.css" rel="stylesheet" type="text/css" media="all"/>
    <script src="/admin/js/jquery.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="/admin/js/bootstrap.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="/admin/js/pintuer.js"></script>
    <title>编辑影片信息</title>
    <style type="text/css">
        .occupation-box {
            border: 1px solid #ddd;
            width: 300px !important;
            height: 100px;
            padding: 20px;
        }

        .occupation-box > label {
            margin-right: 22px;
        }
        .body-content label {
            font-size: 1.2rem;
            vertical-align: middle;
        }
        .field .input {
            width: 600px;
        }
        .field label {
            font-size: 16px;
        }
    </style>
</head>
<body>
<div class="panel admin-panel">
    <div class="panel-head"><strong><span class="icon-pencil-square-o"></span> 影片信息</strong></div>
    <div id="app" class="body-content">
        <!-- 测试影片播放链接的模态框 Modal -->
        <div class="modal modal-lg fade" id="playModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-fullscreen">
                <div class="modal-content">
                    <div class="modal-header">
                        <h1 class="modal-title fs-5" id="playModalLabel">视频播放测试</h1>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <video id="player" v-bind:src="film.playLink" controls style="width: 100%; height: 100%;"></video>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    </div>
                </div>
            </div>
        </div>
        <!-- // 查询并选中影人的模态框 Modal-->
        <!-- 查询并选中影人的模态框 Modal -->
        <div class="modal modal-lg fade" id="selectMakerModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
                <div class="modal-content">
                    <div class="modal-header">
                        <h1 class="modal-title fs-5" id="exampleModalLabel">选择影人</h1>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <ul class="search">
                            <li>
                                <input class="input" type="text" placeholder="输入影人姓名快速检索" v-model="keyword" @keyup.enter="searchFilmMaker">
                            </li>
                            <li>
                                <button class="button border-blue" @click="searchFilmMaker">搜索</button>
                            </li>
                        </ul>
                        <table class="table table-hover">
                            <thead>
                            <th>姓名</th>
                            <th>头像</th>
                            <th>操作</th>
                            </thead>
                            <tbody>
                            <!-- 1. v-model 改为 v-for；2. makerlist 改为 makerList（驼峰命名）；3. 添加 :key 提高性能 -->
                            <tr style="text-align: center;" v-for="item in makerList" :key="item.id">
                                <td>{{item.name}}</td>
                                <td>
                                    <img v-bind:src="item.avatar" height="80" alt="">
                                </td>
                                <td>
                                    <button class="btn btn-success btn-sm" @click="selectMaker(item)">选中</button>
                                </td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    </div>
                </div>
            </div>
        </div>
        <!-- // 查询并选中影人的模态框 Modal-->
        <form method="post" class="form-x" id="form" @submit.prevent="submit">
            <div class="form-group">
                <div class="label">
                    <label>影片名称：</label>
                </div>
                <div class="field">
                    <input type="hidden" name="id" v-model="film.id" />
                    <input type="text" class="input" name="name" v-model="film.name"  />
                    <div class="tips"></div>
                </div>
            </div>
            <!--封面-->
            <div class="form-group">
                <div class="label">
                    <label>封面：</label>
                </div>
                <div class="field">
                    <input v-model="film.cover" type="text" name="avatar" class="input" style="width: 600px;" readonly>
                    <img class="img-upload" v-show="film.cover != null" v-bind:src="film.cover" height="80" alt="">
                    <input type="file" id="cover" name="cover" accept="image/*" @change="uploadResource">
                </div>
            </div>
            <!--封面-->
            <div class="form-group">
                <div class="label">
                    <label>海报：</label>
                </div>
                <div class="field">
                    <input v-model="film.post" type="text" name="avatar" class="input" style="width: 600px;" readonly>
                    <img class="img-upload" v-show="film.post != null" v-bind:src="film.post" alt="">
                    <input type="file" id="post" name="post" accept="image/*" @change="uploadResource">
                </div>
            </div>
            <!--视频-->
            <div class="form-group">
                <div class="label">
                    <label>视频：</label>
                </div>
                <div class="field">
                    <input v-model="film.playLink" type="text" name="avatar" class="input" style="width: 600px;" readonly>
                    <input type="file"  id="playLink" name="playLink" accept="video/MP4V-ES" @change="uploadResource">
                    <a class="btn btn-link" data-bs-toggle="modal" data-bs-target="#playModal">测试视频</a>
                </div>
            </div>
            <!--导演-->
            <div class="form-group">
                <div class="label">
                    <label>选择导演：</label>
                </div>
                <div class="field">
                    <h5>
                        <span v-for="(item, i) in film.makerList" class="badge bg-blue" title="双击移除该影人"v-if="item.role=='导演'"
                              style="margin: 2px 2px; cursor: pointer;" @dblclick="removeFilmMaker(i)">{{item.name}}</span>
                    </h5>
                    <button type="button" class="button border-red" data-bs-toggle="modal" data-bs-target="#selectMakerModal" data-bs-whatever="导演">添加</button>
                    <div class="tips"></div>
                </div>
            </div>
            <!--编剧-->
            <div class="form-group">
                <div class="label">
                    <label>选择编剧：</label>
                </div>
                <div class="field">
                    <h5>
                        <span v-for="(item, i) in film.makerList" class="badge bg-blue" title="双击移除该影人"v-if="item.role=='编剧'"
                              style="margin: 2px 2px; cursor: pointer;" @dblclick="removeFilmMaker(i)">{{item.name}}</span>
                    </h5>
                    <button type="button" class="button border-blue" data-bs-toggle="modal" data-bs-target="#selectMakerModal" data-bs-whatever="编剧">添加</button>
                    <div class="tips"></div>
                </div>
            </div>
            <!--演员-->
            <div class="form-group">
                <div class="label">
                    <label>选择演员：</label>
                </div>
                <div class="field">
                    <h5>
                        <span v-for="(item, i) in film.makerList" class="badge bg-blue" title="双击移除该影人"v-if="item.role=='演员'"
                              style="margin: 2px 2px; cursor: pointer;" @dblclick="removeFilmMaker(i)">{{item.name}}</span>
                    </h5>
                    <button type="button" class="button border-green" data-bs-toggle="modal" data-bs-target="#selectMakerModal" data-bs-whatever="演员">添加</button>
                    <div class="tips"></div>
                </div>
            </div>
<!--            影片类别-->
            <div class="form-group">
                <div class="label">
                    <label>影片类别：</label>
                </div>
                <div class="field">
                    <label style="margin-left: 20px;" class="checkbox-inline" v-for="item in categoryList">
                        <input type="checkbox" v-bind:value="item.id" v-model="film.categoryIds" >{{item.name}} 制作中

                    </label>
                </div>
            </div>
            <!--影片状态-->
            <div class="form-group">
                <div class="label">
                    <label>影片状态：</label>
                </div>
                <div class="field">
                    <label class="checkbox-inline">
                        <input type="radio" value="0" v-model="film.status" > 制作中
                    </label>
                    <label class="checkbox-inline">
                        <input type="radio" value="1" v-model="film.status" > 待上映
                    </label>
                    <label class="checkbox-inline">
                        <input type="radio" value="2" v-model="film.status" > 正在上映
                    </label>
                    <label class="checkbox-inline">
                        <input type="radio" value="3" v-model="film.status" > 已经停播
                    </label>
                </div>
            </div>
            <!--上映日期-->
            <div class="form-group">
                <div class="label">
                    <label>上映日期：</label>
                </div>
                <div class="field">
                    <input class="input" type="date" v-model="film.releaseDate" >
                </div>
            </div>
            <!--发行国家-->
            <div class="form-group">
                <div class="label">
                    <label>发行国家：</label>
                </div>
                <div class="field">
                    <input class="input" type="text" name="country" v-model="film.country">
                </div>
            </div>
            <!--购票链接-->
            <div class="form-group">
                <div class="label">
                    <label>购票链接：</label>
                </div>
                <div class="field">
                    <input class="input" type="text" v-model="film.ticketLink" >
                </div>
            </div>
            <!--放映版本-->
            <div class="form-group">
                <div class="label">
                    <label>放映格式/版本：</label>
                </div>
                <div class="field">
                    <input class="input" type="text" name="version" v-model="film.version" >
                </div>
            </div>
            <!--累计票房-->
            <div class="form-group">
                <div class="label">
                    <label>累计票房：</label>
                </div>
                <div class="field">
                    <input class="input" type="text" v-model="boxOffice"  placeholder="单位:万元">
                </div>
            </div>
            <!--语言-->
            <div class="form-group">
                <div class="label">
                    <label>语言：</label>
                </div>
                <div class="field">
                    <input class="input" type="text" name="language" v-model="film.language">
                </div>
            </div>
            <!--时长-->
            <div class="form-group">
                <div class="label">
                    <label>时长：</label>
                </div>
                <div class="field">
                    <input class="input" type="text" v-model="film.length" placeholder="单位：分钟" >
                </div>
            </div>
            <!--简介-->
            <div class="form-group">
                <div class="label">
                    <label>简介：</label>
                </div>
                <div class="field">
                    <textarea class="input" type="text" style="height: 200px;" v-model="film.info" ></textarea>
                </div>
            </div>

            <div class="form-group">
                <div class="label">
                    <label></label>
                </div>
                <div class="field">
                    <button class="button border-main icon-check-square-o" type="submit"> 提交</button>
                    <button class="button border-red icon-tags" type="button" onclick="window.history.go(-1);"> 返回
                    </button>
                </div>
            </div>
        </form>
    </div>

    <script type="text/javascript" src="/public/js/vue.js"></script>
    <script type="text/javascript" src="/public/js/axios.js"></script>
    <script type="text/javascript" src="/public/js/axios-config.js"></script>

    <script>
        /**
         * 将信息中的换行符替换成 <br/> 标签
         * @param text 源数据
         * @returns {*} 替换之后的数据
         */
        function convertTextareaToBR(text) {
            return text.replace(/\r\n/g,'<br/>').replace(/\n/g,'<br/>').replace(/\s/g,' ');
        }
        function getUrlParam(name) {
            const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
            const r = window.location.search.substr(1).match(reg);
            return r ? decodeURIComponent(r[2]) : null;
        }
    </script>
    <script>
        new Vue({
            el: '#app',
            data: {
                keyword: null,
                categoryList: [],
                makerList: [],
                recipient: null, // 关键：移到Vue的data中，避免全局变量
                film: {
                    categoryIds: [],
                    makerList: [],
                    cover: null,
                    post: null,
                    playLink: null
                },
                //boxOffice: '',
                submitUrl: "/api/v1/film/save"
            },
            methods: {
                // 新增：加载影片详情（修改时调用）
                loadFilmDetail(Id) {
                    // 调用后端详情接口（需替换为实际接口地址）
                    axios.get(`/api/v1/film/detail/${Id}`)
                        .then(res => {
                            const filmData = res.data; // 假设后端直接返回影片详情对象
                            // 1. 回显基本信息到film对象
                            this.film = {
                                ...filmData,
                                // 确保categoryIds和makerList默认是数组（避免undefined报错）
                                categoryIds: filmData.categoryIds || [],
                                makerList: filmData.makerList || []
                            };
                            // 2. 回显票房（单独的boxOffice变量）
                            this.boxOffice = filmData.boxOffice ? filmData.boxOffice.toString() : '';
                            // 3. 调整提交URL为“更新接口”（而非新增）
                            this.submitUrl = `/api/v1/film/update`; // 后端的更新接口
                        })
                        .catch(err => {
                            console.error('加载影片详情失败', err);
                            alert('加载数据失败：' + (err.response?.data?.message || '网络错误'));
                        });
                },
                submit() {
                    // 1. 基础数据验证
                    if (!this.film.name) {
                        alert('请输入影片名称');
                        return;
                    }
                    if (!this.film.releaseDate) {
                        alert('请选择上映日期');
                        return;
                    }
                    if (this.film.makerList.length === 0) {
                        alert('请至少添加一位影人（导演/编剧/演员）');
                        return;
                    }

                    // 2. 整理提交数据（根据后端接口要求调整）
                    const submitData = {
                        ...this.film,
                        boxOffice: this.boxOffice ? parseFloat(this.boxOffice) : 0, // 处理票房数据
                        length: this.film.length ? parseInt(this.film.length) : 0 // 处理时长数据
                    };

                    // 3. 提交到后端
                    axios.post(this.submitUrl, submitData)
                        .then(res => {

                                alert('保存成功');
                                // 提交成功后返回列表页
                                window.history.go(-1);

                        })
                        .catch(err => {
                            console.error('提交失败', err);
                            alert('网络错误，保存失败');
                        });
                },
                loadCategoryList() {
                    axios.get('/api/v1/category/list')
                        .then(res => {
                            // 直接判断返回是否为数组
                            if (Array.isArray(res.data)) {
                                this.categoryList = res.data; // 直接赋值数组
                            } else {
                                alert('加载分类失败：返回数据不是列表');
                            }
                        })
                        .catch(err => {
                            alert('加载分类失败：' + err.message);
                        });
                },
                uploadResource(event) {
                    const formData = new FormData();
                    // 将参数名从'file'改为'multipartFile'，与后端保持一致
                    formData.append('multipartFile', event.target.files[0]);

                    axios.post('/api/v1/file/upload', formData, {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    })
                        .then(res => {
                            console.log('上传成功', res.data);
                            // 根据上传的类型（封面/海报/视频）更新对应属性
                            const fileType = event.target.name; // 获取input的name属性（cover/post/playLink）
                            this.film[fileType] = res.data; // 假设后端返回的是文件URL
                        })
                        .catch(err => {
                            console.error('上传失败', err);
                        });
                },
                searchFilmMaker() {
                    let url = '/api/v1/maker/page';
                    let params = {
                        "pageNum": 1,
                        "pageSize": 10,
                        "name": this.keyword
                    };
                    axios.post(url, params)
                        .then(res => {
                            // 修复：res.data.List → res.data.data.list（根据实际接口调整）
                            this.makerList = res.data?.list || [];
                        })
                        .catch(err => {
                            console.error('搜索影人错误：', err);
                        });
                }, selectMaker(item) {
                    // 1. 校验角色是否已选择（避免recipient为空）
                    if (!this.recipient) {
                        alert('请先通过"添加"按钮选择正确的角色（导演/编剧/演员）');
                        return;
                    }

                    // 2. 避免重复添加同一角色的同一影人
                    const isDuplicate = this.film.makerList.some(
                        maker => maker.makerId === item.id && maker.role === this.recipient
                    );
                    if (isDuplicate) {
                        alert(`${item.name} 已添加为 ${this.recipient}`);
                        return;
                    }

                    // 3. 正确添加影人，确保role字段有值
                    this.film.makerList.push({
                        makerId: item.id,    // 影人ID（对应后端film_maker表的maker_id）
                        name: item.name,     // 影人姓名（冗余，方便前端显示）
                        role: this.recipient // 角色（导演/编剧/演员，对应后端film_maker表的role）
                    });

                    // 4. 关闭模态框
                    const selectModal = bootstrap.Modal.getInstance(document.getElementById('selectMakerModal'));
                    selectModal.hide();
                },
                removeFilmMaker(index) {
                    // 从film.makerList中删除对应索引的元素
                    this.film.makerList.splice(index, 1);
                }
            },

            mounted() {
                this.loadCategoryList(); // 加载分类列表（原有逻辑）

                // 新增：解析URL中的影片ID，判断是否为修改
                const filmId = getUrlParam('id'); // 获取URL中的id参数
                if (filmId) {
                    // 如果有id，说明是修改，加载详情
                    this.loadFilmDetail(filmId);
                } else {
                    // 如果没有id，说明是新增，初始化默认值（可选）
                    this.film.status = 0; // 默认状态为“制作中”
                }

                // 修复：模态框事件绑定移到此处
                setTimeout(() => {
                    const playModal = document.getElementById('playModal');
                    if (playModal) {
                        // 视频播放相关事件...
                    }
                    const selectMakerModal = document.getElementById('selectMakerModal');
                    if (selectMakerModal) {
                        // 影人选择相关事件...
                    }
                }, 0);
            }
        });
    </script>

    <script>
        const playModal = document.getElementById('playModal')
        const mediaPlayer = document.getElementById('player')

        // 打开模态框时自动播放
        playModal.addEventListener('shown.bs.modal', () => {
            mediaPlayer.play()
        })
        // 关闭模态框时自动暂停
        playModal.addEventListener('hidden.bs.modal', () => {
            mediaPlayer.pause()
        })
        // 声明全局变量用来保存影人身份
        var recipient = null;
        // 全局脚本中找到模态框事件绑定的代码，修改如下
        const exampleModal = document.getElementById('selectMakerModal');
        // 获取Vue实例（通过id选择器，确保和页面中的#app对应）
        const vm = document.querySelector('#app').__vue__;

        exampleModal.addEventListener('show.bs.modal', event => {
            const button = event.relatedTarget;
            // 给Vue实例的recipient赋值，而非全局变量
            vm.recipient = button.getAttribute('data-bs-whatever');
            const modalTitle = exampleModal.querySelector('.modal-title');
            modalTitle.textContent = `选择 ${vm.recipient}`;
        })
        // 如果用户填写了多个出品国家 语言 版本 自动将空格改为/
        document.querySelector("[name=country]").addEventListener('keyup',function (event){
            let val = event.target.value.replaceAll(' ','/')
            event.target.value = val
        })
        document.querySelector("[name=language]").addEventListener('keyup',function (event){
            let val = event.target.value.replaceAll(' ','/')
            event.target.value = val
        })
        document.querySelector("[name=version]").addEventListener('keyup',function (event){
            let val = event.target.value.replaceAll(' ','/')
            event.target.value = val
        })
        // 在Vue实例外部添加URL参数解析方法

    </script>
</div>
</body>
</html>